<script setup lang="js">
    import axios from 'axios'
    import { useRouter } from 'vue-router';
    import { ElMessage } from "element-plus";
    import { inject, computed, ref, defineProps } from 'vue'
    import { fileIco } from '../../utils'
    import request from '../../request/axios'
    import { PATH_URL } from '../../request/axios/service.js'
    import buildKnowledge from '../../components/buildKnowledge/index.vue'
    const router = useRouter();

    // 接收父组件参数
    const props = defineProps({
        chatType: {
            type: String,
            required: true
        },
        termination: {
            type: Boolean,
            required: false
        },
        modelType: {
            type: String,
            required: 'deepseek-v3'
        },
        chatMessageType: {
            type: Boolean,
            required: false
        },
        replyType: {
            type: Boolean,
            required: false
        }
    });

    const chatMessage = inject('chatMessage') // 向父组件传递消息
    const chatTermination = inject('chatTermination') // 向父组件传递终止消息
    const fileBoxShow = inject('fileBoxShow') // 向父组件传递是否有文件
    const knowledge = inject('knowledge') // 向父组件传递点击知识库配置

    const thinkingShow = ref(false)
    const fileList = ref([]) // 上传文件的列表
    const model = ref(props.modelType) // 模型
    const messageText = ref('')
    const clickChat = () => {
        if (props.replyType) return ElMessage.warning("模型正在回答，请耐心等待！")
        if (messageText.value == '' || messageText.value == '\n') {
            messageText.value = ''
            return ElMessage.warning("请输入内容")
        }
        if (props.modelType == 'Deepseek') {
            if (thinkingShow.value) {
                model.value = 'deepseek-r1'
            } else {
                model.value = 'deepseek-v3'
            }
        }

        const params = {}
        params.content = messageText.value
        params.model = model.value || 'deepseek-v3' // 模型
        params.session_id = localStorage.getItem("sessionId") ? localStorage.getItem("sessionId") : ''; // 会话id聊天id
        localStorage.removeItem("sessionId")
        if (fileList.value.length > 0) {
            params.files = JSON.stringify(fileList.value) // 文件列表
        }
        if (chatMessage) {
            chatMessage(params)
            messageText.value = ''
            fileList.value = []
            if (fileBoxShow) {
                fileBoxShow(fileList.value.length)
            }
        }
    }


    // 输入框回车键监听
    const textareaEnterKeyDown = (e) => {
        // 如果是 Shift + Enter 组合键，则换行
        if (e.key === 'Enter' && e.shiftKey) {
            e.preventDefault()
            return
        }
        // 如果是 Enter 键，则发送请求
        if (e.keyCode === 13) {
            clickChat()
            e.preventDefault()
            return
        }
    }

    const newChat = () => {
        router.push('/initialization')
    }

    // 初始化icon
    const formattingIcon = (name) => {
        if (!name) return
        return fileIco(name)
    }

    const fileIcon = (name) => {
        const icon = formattingIcon(name)
        const image = new URL(`../../assets/image/file-ico/ico-${icon}.png`, import.meta.url).href
        return image
    }

    // 终止发送消息
    const clickTermination = () => {
        if (chatTermination) {
            chatTermination(true)
        }
    }

    // 文件删除
    const clickFileDel = (index) => {
        fileList.value.splice(index, 1)
        if (fileBoxShow) {
            fileBoxShow(fileList.value.length)
        }
    }

    // 文件上传
    const handleUpload = async (file) => {
        if (fileList.value.length >= 3) return ElMessage.warning("最多上传三个文件")

        fileList.value.push({
            file_name: file.file.name,
            oss_upload_files_path: "",
            status: 0, // 0 上传中 1 上传成功 2 上传失败
        })
        const url = PATH_URL + '/v1/api-upload-oss'
        const formData = new FormData()
        formData.append('file[]', file.file, file.name)
        axios
            .post(url, formData, {
                headers: {
                    'Authorization': localStorage.getItem("token") || '',
                    'Content-Type': 'multipart/form-data'
                }
            })
            .then((response) => {
                if (response.data.code == 200) {
                    fileList.value.forEach((_, i) => fileList.value[i].status = 1);
                    fileList.value[fileList.value.length - 1].oss_upload_files_path = response.data.data[0].oss_upload_files_path
                    if (fileBoxShow) {
                        fileBoxShow(fileList.value.length)
                    }
                    return
                }
                fileList.value[fileList.value.length - 1].status = 2
            })
            .catch((error) => {
                console.log('Upload error:', error)
            })
    }
    // 超出限制的回调
    const handleExceed = (files, uploadFiles) => {
        if (fileList.value.length + files.length >= 3 || fileList.value.length >= 3 || files.length + uploadFiles.length > 4) return ElMessage.warning("最多上传三个文件")
    }

    // 配置
    const buildKnowledgeRef = ref(null);
    const clickConfiguration = async () => {
        
        // ElMessage.warning('知识库相关功能正在开发中，敬请期待')
        // return
        try {
            const res = await request.postV2({ url: '/v1/api-user-prompt' })
            if (res.code == 200) {
                if (res.data.is_prompt_status == 1) return ElMessage.warning(res.data.prompt)
                if (props.chatMessageType) {
                    if (knowledge) {
                        knowledge()
                    }
                    return
                }
                if (buildKnowledgeRef.value) return buildKnowledgeRef.value.setCheckedVisible();
            }
        } catch (error) {
            console.log(error)
        }

    }
</script>

<template>
    <div>
        <!-- <div class="new-chat" v-if="props.chatType != 'newChat'" @click="newChat">开启新对话</div> -->
        <!-- 文件列表 -->
        <div class="file-content" v-if="fileList.length > 0">
            <div class="file-item" v-for="(item, index) in fileList" :key="index">
                <img :src="fileIcon(item.file_name)" style="width: 20px;">
                <div class="file-message">
                    <div class="file-name">{{ item.file_name }}</div>
                    <div class="file-tips">
                        <Loading style="width: 16px;" v-if="item.status == 0" />
                        {{item.status == 0 ? '上传中' : item.status == 1 ? '上传成功' : '上传失败'}}
                    </div>
                </div>
                <CircleCloseFilled @click="clickFileDel(index)" class="icon-close" />
            </div>
        </div>
        <!-- 消息输入框 -->
        <div class="input-content">
            <div class="input-box">
                <el-input v-model="messageText" :rows="3" class="input-textarea" type="textarea"
                    placeholder="请输入您的问题，可回答与DataMed数据库中国注册产品相关问题" @keyup.enter="textareaEnterKeyDown" />
            </div>
            <div class="input-btn">
                <div v-if="props.modelType == 'Deepseek'" :class="['btn-item', thinkingShow ? 'btn-item-active' : '']"
                    @click="thinkingShow = !thinkingShow">
                    <img v-if="thinkingShow" src="../../assets/image/icon/thinking-icon.png" />
                    <img v-else src="../../assets/image/icon/thinking.png" />
                    深度思考
                </div>
                <div v-else></div>
                <div class="icon-box">
                    <img src="../../assets/image/icon/collection-icon.png"
                        style="width: 30px;height: 30px;margin-top: 8px;" @click="clickConfiguration" />
                    <el-upload action="#" :show-file-list="false" :http-request="handleUpload"
                        accept=".docx,.pdf,.xlsx,.xls,.excel,.txt,.pptx" :limit="3" :multiple="true"
                        :on-exceed="handleExceed">
                        <img src="../../assets/image/icon/file.png" />
                    </el-upload>
                    <img v-if="messageText == '' && !props.termination" src="../../assets/image/icon/no-send.png"
                        style="cursor: no-drop;" />
                    <img v-if="messageText != '' && !props.termination" src="../../assets/image/icon/send.png"
                        @click="clickChat" />
                    <img v-if="props.termination" src="../../assets/image/icon/termination.png"
                        @click="clickTermination" />
                </div>
            </div>
        </div>
        <!-- 配置绑定 -->
        <buildKnowledge ref="buildKnowledgeRef" />
    </div>
</template>

<style scoped lang="scss">
    .icon-box {
        cursor: pointer;
        display: flex;

        img {
            width: 40px;
            height: 40px;
            margin-right: 4px;
        }
    }

    .new-chat {
        width: 160px;
        height: 38px;
        color: #1a2D66B3;
        line-height: 38px;
        text-align: center;
        margin: 0 auto;
        cursor: pointer;
        margin-bottom: 12px;
        border-radius: 12px;
        background: rgba(45, 102, 179, 0.1);
        border: 1px solid #1a2D66B3;
    }

    .file-content {
        height: 100px;
        padding-top: 1px;
        border-radius: 29px 29px 0 0;
        margin-bottom: -30px;
        background-color: #FAFAFA;
        display: flex;
        align-items: flex-start;

        .file-item {
            width: 200px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 10px 0 10px 20px;
            border-radius: 11px;
            background: #ECF4F4;
            cursor: pointer;
            position: relative;

            .file-message {
                margin-left: 8px;
                font-size: 12px;
                color: #999999;

                .file-name {
                    width: 150px;
                    font-size: 14px;
                    color: #3D3D3D;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }

                .file-tips {
                    display: flex;
                    align-items: center;
                    font-size: 12px;
                    color: #999999;
                }
            }

            &:hover {
                .icon-close {
                    display: block;
                }
            }


            .icon-close {
                display: none;
                position: absolute;
                width: 20px;
                height: 20px;
                top: -10px;
                right: -10px;
                color: rgb(253, 58, 58);
            }
        }
    }

    .input-content {
        height: 140px;
        border-radius: 29px;
        background: #FFFFFF;
        overflow: hidden;
        position: relative;
        box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.06);

        .input-box {
            /* padding: 6px; */

            :deep(.el-textarea__inner) {
                box-shadow: none;
                border-radius: 0;
                padding: 0 18px 0;
                border-bottom: none;
                margin-top: 12px;
            }

        }

        .input-btn {
            display: flex;
            align-items: end;
            justify-content: space-between;
            padding: 0 26px 10px;
            position: absolute;
            width: 94%;
            bottom: 0;
            left: 0;
            background-color: #fff;

            .btn-item {
                cursor: pointer;
                color: #2D66B3;
                padding: 4px 14px;
                font-size: 12px;
                border-radius: 18px;
                display: flex;
                align-items: center;
                border: 1px solid #2D66B3;

                img {
                    width: 16px;
                    height: 16px;
                    margin-right: 4px;
                }
            }

            .btn-item-active {
                color: #fff;
                background-color: #2D66B3;
            }
        }
    }

    .input-box::after {
        content: "";
        position: absolute;
        width: 20px;
        height: 100%;
        top: 0;
        right: 0;
        z-index: 999;
        background-color: #fff;
    }
</style>